package chapter07

object Test14_HighLevelFunction_Map {
  def main(args: Array[String]): Unit = {
    val list = List(1, 2, 3, 4, 5, 6, 7, 8, 9)

    // 1. 过滤
    println(list.filter((item: Int) => item % 2 == 0))
    println(list.filter(_ % 2 == 0))
    //2. map
    println(list.map(_ * 2))
    // 3.扁平化
    // 3.1
    val nestedList: List[List[Int]] = List(List(1, 2, 3), List(4, 5), List(6, 7, 8, 9))
    val flatList = nestedList(0) ::: nestedList(1) ::: nestedList(2)
    println(flatList)

    //3.2
    println(nestedList.flatten)

    // 4.扁平映射
    // 当一组字符串进行分词,并保存成单词的列表
    // 4.1
    val strings: List[String] = List("hello world", "hello scala", "hello java", "we study")
    println(strings.map(_.split(" ")) // 分词
      .flatten) //打散扁平化
    // 4.2
    println(strings.flatMap(_.split(" ")))

    // 5.分组
    //分成奇偶两组
    println(list.groupBy(_ % 2))
    println(list.groupBy(item => if (item % 2 == 0) "偶数" else "奇数"))

    // 给定一组词汇,按单词首字母进行分组
    val wordList = List("china", "america", "alice", "canada", "cary", "bob", "japan")
    println(wordList.groupBy(_.charAt(0)))
  }

}
